package com.inspur.edp.common.expr.expresses.method;


import com.inspur.edp.common.expr.Express;
import com.inspur.edp.common.expr.ExpressDSLGenerator;
import com.inspur.edp.common.expr.ExpressDSLGeneratorMgr;
import com.inspur.edp.common.expr.ast.ASTContext;
import com.inspur.edp.common.type.Method;
import com.inspur.edp.common.type.Type;
import com.inspur.edp.common.type.cache.TypeThreadCache;
import com.inspur.edp.common.type.utils.TypeUtil;

/**
 * @author lizhaorui
 * @description TODO
 * @date 2024/12/17 10:39
 */
public class MethodInvokeDSL implements ExpressDSLGenerator {

    @Override
    public String getKind() {
        return MethodInvokeExpr.KIND;
    }

    @Override
    public String generate(ASTContext context, Express express) {
        MethodInvokeExpr methodInvokeExpr = (MethodInvokeExpr) express;
        String objectUrl = "";
        String methodCode = methodInvokeExpr.getMethodCode();
        if (methodInvokeExpr.getExpress() != null) {
            objectUrl = ExpressDSLGeneratorMgr.generateDsl(context, methodInvokeExpr.getExpress());
        } else {
            String typeUrl = methodInvokeExpr.getTypeUrl();
            context.addImport(typeUrl);
            Type type = TypeThreadCache.getByUrl(typeUrl);
            Method method = type.getMethod(methodCode);
            //分两种情况
            if (method.isStatic()) {
                //1.该方法为静态方法
                objectUrl = TypeUtil.getTypeCode(typeUrl);
            } else {
                //2.该方法非静态方法
                objectUrl = String.format("new %s()", TypeUtil.getTypeCode(typeUrl));
            }
        }
        StringBuilder sb = new StringBuilder();
        if (methodInvokeExpr.getParameters() != null || methodInvokeExpr.getParameters().size() > 0) {
            int index = 0;
            for (MethodInvokeExpr.MethodParameter methodParameter : methodInvokeExpr.getParameters()) {
                Express expressItem = methodParameter.getValue();
                if (index > 0) {
                    sb.append(",");
                }
                sb.append(ExpressDSLGeneratorMgr.generateDsl(context, expressItem));
                index++;
            }
        }
        return String.format("%s.%s(%s)", objectUrl, methodInvokeExpr.getMethodCode(), sb.toString());
    }
}
